package com.j;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ImportXml {

	public static void main(String[] args) throws ParserConfigurationException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		DocumentBuilder db = factory.newDocumentBuilder();
		Document xmldoc = db.newDocument();
	

		Element provinceDoc=xmldoc.createElement("province");
		provinceDoc.setAttribute("id", "1");
		provinceDoc.setAttribute("name", "福建省");
		Element cityDoc=xmldoc.createElement("city");
		cityDoc.setAttribute("id", "1");
		cityDoc.setAttribute("name", "福州市");
		provinceDoc.appendChild(cityDoc);
	
		
	
		xmldoc.appendChild(provinceDoc);
		
		saveXml("t.xml", xmldoc);

	}

	static void test() {
		Connection conn = DBUtil.getInstance().getConn();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement("select *from user");
			rs = pstmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getObject(1));
				System.out.println(rs.getObject(2));
			}

		} catch (SQLException e) {
			e.printStackTrace();

		} finally {
			DBUtil.getInstance().closeResource(conn, pstmt, rs);
		}
	}

	/**
	 * 将Document输出到文件
	 * 
	 * @param fileName
	 * @param doc
	 */
	 static void saveXml(String fileName, Document doc) {
		TransformerFactory transFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = transFactory.newTransformer();
			transformer.setOutputProperty("indent", "yes");
			DOMSource source = new DOMSource();
			source.setNode(doc);
			StreamResult result = new StreamResult();
			result.setOutputStream(new FileOutputStream(fileName));

			transformer.transform(source, result);

		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}
